package com.itheima.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.TagMapper;
import com.itheima.pojo.Tag;
import com.itheima.utils.DateUtils;
import com.itheima.utils.IdWorker;
import com.itheima.utils.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @Description:
 * @Version: V1.0
 */
@Service
public class TagService {

    @Autowired
    private TagMapper tagMapper;

    public void add(Tag tag) {
        if (tag != null) {
            if (tag.getUid() == null) {
                tag.setUid(String.valueOf(new IdWorker().nextId()));
            }
            if (tag.getStatus() == null) {
                tag.setStatus(1);
            }
            if (tag.getSort() == null) {
                tag.setSort(1);
            }
            if (tag.getContent() == null) {
                tag.setContent("");
            }
            tag.setClickCount(0);
            Date time = DateUtils.strToDateTime(DateUtils.getNowTime());
            tag.setCreateTime(time);
            tag.setUpdateTime(time);
            tagMapper.insertSelective(tag);
        }
    }

    public void edit(Tag tag) {
        Date time = DateUtils.strToDateTime(DateUtils.getNowTime());
        tag.setUpdateTime(time);
        tagMapper.updateByPrimaryKeySelective(tag);
    }

    public void deleteBatch(List<Tag> list) {
        if (list != null && list.size() > 0) {
            for (Tag Tag : list) {
                if (Tag != null) {
                    tagMapper.deleteByPrimaryKey(Tag.getUid());
                }
            }
        }
    }

    public PageResult<Tag> getList(Tag tag) {
        PageHelper.startPage(tag.getCurrentPage(), tag.getPageSize());
        Page<Tag> Tags = (Page<Tag>) tagMapper.selectAll();
        return new PageResult<Tag>(Tags.getTotal(), Tags.getResult());
    }

    public void stick(Tag tag) {
        int max = tagMapper.findMaxSort();
        Tag tag1 = tagMapper.selectByPrimaryKey(tag.getUid());
        Integer sort = tag1.getSort();
        if (sort <= max) {
            tag1.setSort(max + 1);
        }
        tagMapper.updateByPrimaryKey(tag1);
    }

    public void tagSortByCite() {
        List<Tag> Tags = tagMapper.selectAll();
        for (Tag tag : Tags) {
            tag.setSort(0);
            tagMapper.updateByPrimaryKeySelective(tag);
            tag.setSort(tagMapper.citeNum(tag.getUid()));
            tagMapper.updateByPrimaryKeySelective(tag);
        }
    }

    public void tagSortByClickCount() {
        List<Tag> Tags = tagMapper.selectAll();
        for (Tag tag : Tags) {
            tag.setSort(tag.getClickCount());
            tagMapper.updateByPrimaryKeySelective(tag);
        }
    }

}
